/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gourmetgrossisten;

import db.DatabaseConnect;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @author Hans
 */
public class GourmetGrossisten extends Application {

    private boolean loggedin;
    private DatabaseConnect db;
    private String email;
    private String password;
    private TextField emailField;
    private PasswordField passwordField;
    private Button loginButton;
    private final TextArea dumpArea;
    private final Button showStorageStatus;
    private final Button showDiscounts;
    private final Button showCategories;
    private final Button showOrders;
    private final Button showOrder;
    private final ComboBox<String> comboOrderID;
    private final StackPane sp1;
    private final StackPane sp2;
    private final StackPane sp3;
    private static final String PREFIX = System.lineSeparator();
    private static final boolean INCLUDECOLUMNLABEL = true;
    private static final boolean INCLUDECOLUMNTYPE = false;

    public GourmetGrossisten() {
        dumpArea = new TextArea();
        sp1 = new StackPane();
        sp2 = new StackPane();
        sp3 = new StackPane();
        loginButton = new Button("Log ind");
        passwordField = new PasswordField();
        emailField = new TextField("indkob@monello.dk");

        db = new DatabaseConnect("gourmet");
        try {
            db.connectToDB();
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(GourmetGrossisten.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("connection faild");
        }

        dumpArea.setEditable(false);
        dumpArea.setFocusTraversable(false);
        loginButton.setOnAction(event -> {
            attemptLogin();
        });
        emailField.setOnAction(event -> {
            attemptLogin();
        });
        passwordField.setOnAction(event -> {
            attemptLogin();
        });
        showStorageStatus = new Button("Hent Lager status");
        showStorageStatus.setOnAction(event -> {
            callDB("showStorageStatus", PREFIX, getArgs());
        });
        showStorageStatus.setPrefSize(175, 20);
        showDiscounts = new Button("Hent discounts");
        showDiscounts.setOnAction(event -> {
            callDB("showDiscounts", PREFIX, getArgs());
        });
        showDiscounts.setPrefSize(175, 20);
        
        showCategories = new Button("Hent Kategorier");
        showCategories.setOnAction(event -> {
            callDB("showCategory", PREFIX, getArgs());
        });
        showCategories.setPrefSize(175, 20);
        
        showOrders = new Button("Hent Ordre");
        showOrders.setOnAction(event -> {
            callDB("showOrders", PREFIX, getArgs());
        });
        showOrders.setPrefSize(175, 20);

        comboOrderID = new ComboBox<>();
        showOrder = new Button("Hent Ordre");
        showOrder.setOnAction(event -> {
            String item = comboOrderID.getSelectionModel().getSelectedItem();
            if (!item.trim().isEmpty()) {
                callDB("showOrder", PREFIX, getArgs(email, password, item));
            }
        });
        showOrder.setPrefSize(125, 20);
    }

    @Override
    public void start(Stage primaryStage) {
        StackPane root = new StackPane();
        Scene scene = new Scene(root, 1600, 900);
        HBox orderBox = new HBox(comboOrderID, showOrder);
        VBox vbox = new VBox(showStorageStatus, showDiscounts, showCategories, showOrders, orderBox);
        vbox.setAlignment(Pos.TOP_CENTER);
        HBox hbox = new HBox(vbox);
        hbox.setAlignment(Pos.CENTER);

        sp1.getChildren().addAll(hbox);
        sp2.getChildren().add(dumpArea);

        hbox.prefWidthProperty().bind(sp1.prefWidthProperty());

        SplitPane splitPane = new SplitPane();
        splitPane.prefWidthProperty().bind(scene.widthProperty());
        splitPane.prefHeightProperty().bind(scene.heightProperty());
        splitPane.setOrientation(Orientation.HORIZONTAL);
        splitPane.setDividerPositions(0.25f, 0.75f);
        splitPane.getStyleClass().add("static-split");
        disableDividers(splitPane);

        SplitPane insideLeftSplitPane = new SplitPane();
        insideLeftSplitPane.setOrientation(Orientation.VERTICAL);
        insideLeftSplitPane.setDividerPositions(0.6f, 0.4f);
        insideLeftSplitPane.getItems().addAll(sp1, sp2);
        insideLeftSplitPane.getStyleClass().add("static-split");
        disableDividers(insideLeftSplitPane);

        splitPane.getItems().addAll(insideLeftSplitPane, sp3);
        root.getChildren().add(splitPane);
        root.getStylesheets().add(GourmetGrossisten.class.getResource("/resources/styles.css").toExternalForm());
        showLogin();

        primaryStage.setTitle("Gourmet!");
        primaryStage.setScene(scene);
        primaryStage.show();

        attemptLogin();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

    private void disableDividers(final SplitPane split) {
        Platform.runLater(() -> {
            split.lookupAll(".split-pane-divider").stream().forEach((div) -> {
                div.setMouseTransparent(true);
            });
        });
    }

    private void attemptLogin() {
        loggedin = false;
        if (emailField.getText().trim().isEmpty()) {
            Platform.runLater(() -> {
                emailField.requestFocus();
            });
        } else if (passwordField.getText().trim().isEmpty()) {
            Platform.runLater(() -> {
                passwordField.requestFocus();
            });
        } else {
            email = emailField.getText();
            password = passwordField.getText();
            try {
                String reply = db.call("login", getArgs(), "", false, false).trim();
                dumpArea.setText(reply);
                if (email.equals(reply)) {
                    loggedin = true;
                    hideLogin();
                }
            } catch (SQLException ex) {
                Logger.getLogger(GourmetGrossisten.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void showLogin() {
        sp3.getChildren().removeAll(sp3.getChildren());
        VBox vbox1 = new VBox(new Label("Email"), new Label("Kodeord"), new Label(""));
        VBox vbox2 = new VBox(emailField, passwordField, loginButton);
        vbox1.setSpacing(12);
        vbox1.setAlignment(Pos.CENTER_RIGHT);
        vbox2.setSpacing(6);
        vbox2.setAlignment(Pos.CENTER);

        HBox hbox = new HBox(vbox1, vbox2);
        hbox.setSpacing(6);
        hbox.setAlignment(Pos.CENTER);
        hbox.prefWidth(150);

        sp3.getChildren().add(hbox);
    }

    private void hideLogin() {
        if (loggedin) {
            sp3.getChildren().removeAll(sp3.getChildren());
            Button logout = new Button("Log ud");
            logout.setOnAction(event -> {
                email = null;
                password = null;
                emailField.setText("");
                passwordField.setText("");
                showLogin();
                dumpArea.setText("Log out");
            });
            VBox vboxRight = new VBox(logout);
            HBox hboxTopRight = new HBox(vboxRight);
            double top, right, bottom, left;
            top = 10;
            right = 10;
            bottom = 2;
            left = 10;
            Insets insets = new Insets(top, right, bottom, left);
            hboxTopRight.setPadding(insets);
            hboxTopRight.setAlignment(Pos.TOP_RIGHT);
            Label customerLabel = new Label("Hej, Kunde.");
            HBox hbox1 = new HBox(customerLabel);
            hbox1.setPadding(insets);
            try {
                customerLabel.setText("Hej, " + db.call("findCustomerName", getArgs(), ".", false, false));
            } catch (SQLException ex) {
                Logger.getLogger(GourmetGrossisten.class.getName()).log(Level.SEVERE, null, ex);
            }
            sp3.getChildren().addAll(hbox1, hboxTopRight);
            try {
                String reply = db.call("getOrdersID", getArgs(), "", false, false).trim();
                String[] split = reply.split(System.lineSeparator());
                ObservableList<String> orderIDs = FXCollections.observableArrayList();
                orderIDs.addAll(Arrays.asList(split));
                comboOrderID.setItems(orderIDs);
                comboOrderID.getSelectionModel().selectFirst();
            } catch (SQLException ex) {
                Logger.getLogger(GourmetGrossisten.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    private void callDB(String call, String prefix, String[] args) {
        try {
            String reply = db.call(call, args, prefix, INCLUDECOLUMNLABEL, INCLUDECOLUMNTYPE);
//                reply = db.call(call, args, "¤", true,true);
//                reply = db.callShowDiscounts(email.getText(), password.getText(), "¤");
            reply = reply.replace("¤", "\n");
            dumpArea.setText(reply);
        } catch (SQLException ex) {
            Logger.getLogger(GourmetGrossisten.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("fucked it up you did");
        }
    }

    private String[] getArgs() {
        return new String[]{email, password};
    }

    private String[] getArgs(String... args) {
        return args;
    }

}
